<?php

class Site extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->service('Service_urls');
        $this->load->service('Service_keywords');
        $this->load->driver('cache');
    }

    public function index($id = 1)
    {
        $id = (int)$id;
        list($info, $tags, $likeUrls) = $this->_siteInfo($id);

        $description = (strlen($info['remark']) <= 25 ? ($info['remark'] . " " . $this->site['desc']) : mb_substr($info['remark'], 0, 80, 'utf-8'));
        $this->assign('title', $info['title']);
        $this->assign('keywords', $info['keywords']);
        $this->assign('description', $description);
        $this->assign('url', $info);
        $this->assign('likeUrls', $likeUrls);
        $this->_makeHtml($id);
        $this->display('site.tpl');
    }

    private function _makeHtml($id)
    {
        ob_start();

        $this->display('site.tpl');

        $str = ob_get_contents();
        if (defined('APPPATH')) {
            $dir = APPPATH . '../static/site/index/';
        } else {
            $dir = dirname(__FILE__) . '../static/site/index/'; // php5.2居然不支持DIR
        }
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
            chmod($dir, 0777);
        }
        file_put_contents("{$dir}{$id}.html", $str);
        if (!empty($info['pinyin'])) {
            file_put_contents("{$dir}{$info['pinyin']}.html", $str);
        }
        ob_end_clean();
    }

    public function redirect($id = 1, $isSearch = 0)
    {
        $id = (int)$id;

        $cacheKey = 'site_redirect_' . $id;
        $url = $this->cache->memcached->get($cacheKey);
        if (empty($url)) {
            $info = $this->Service_urls->get($id, true);
            if ($info['status'] == -1) {// 删除跳转到特殊页
                $info = $this->Service_urls->get(1, true);
            }

            $info['url'] = stripos($info['url'], "http") === false ? "http:" . $info['url'] : $info['url'];
            if ($isSearch) {
                $info['url'] = stripos($info['search'], "http") === false ? "http:" . $info['search'] : $info['search'];
                $info['url'] = sprintf($info['url'], $this->getParams()['keywords']);
            }
            $url = $info['url'];
            $this->cache->memcached->save($cacheKey, $url, 3600);
        }

        // 权重+1
        $this->Service_urls->add_weight($id);

        $this->_bingIndex($id);
        header('X-Robots-Tag: noindex');// 搜索引擎不收录
        redirect($url);
    }

    private function _bingIndex($id)
    {
        $url = "https://idea.dreamthere.cn/site/index/$id.html";
        $this->load->service('Service_bing');
        $this->Service_bing->indexNow($url);
    }

    /**
     * 单页
     * @param string $key
     */
    public function single($key = 'huaban')
    {
        $key = htmlspecialchars($key);
        $info = $this->Service_urls->getInfo(['pinyin' => $key]);
        if (!$info) {
            $info['id'] = 1;
        }
        list($info, $tags, $likeUrls) = $this->_siteInfo($info['id']);
        $description = (strlen($info['remark']) <= 25 ? ($info['remark'] . " " . $this->site['desc']) : mb_substr($info['remark'], 0, 80, 'utf-8'));
        $this->assign('title', $info['title']);
        $this->assign('keywords', $info['keywords']);
        $this->assign('description', $description);
        $this->assign('url', $info);
        $this->assign('likeUrls', $likeUrls);
        $this->display("single.tpl");
    }

    /**
     * 缓存整个site
     * @param $id
     * @return array
     */
    private function _siteInfo($id)
    {
        $info = $this->Service_urls->get($id);
        if ($info['status'] != 0 || $info['show'] != 1) {
            redirect('', 'auto', 404);
        }
        list($tags, $likeUrls) = $this->_getKeywordInfo($id, $info);
        return [$info, $tags, $likeUrls];
    }

    private function _getKeywordInfo($id, $info)
    {
        $tags = $this->Service_keywords->getList(1, ['url_keywords`.`url_id' => $id, 'keywords`.`status' => 0], 40, 'DESC');
        $cond = ['in' => 'AND keywords.keyword in(\'' . implode('\',\'', array_column($tags, 'keyword')) . '\')', 'urls`.`status' => 0, 'urls`.`show' => 1];
        $list = $this->Service_keywords->getListByKeyword(1, $cond, 24);
        // 没有keyword 去分类
        if (empty($list)) {
            $list = $this->Service_urls->getList(1, ['cate' => $info['cate'], 'status' => 0, 'show' => 1], 24);
        }

        $likeUrls = [];
        foreach ($list as $key => &$url) {
            $url['url'] = '/site/index/' . $url['id'] . '.html';
            if ($url['id'] == $id) {
                unset($list[$key]);
            } else {
                $likeUrls[$url['id']] = $url;
            }
        }
        return [$tags, $likeUrls];
    }
}
